class Prayer < ActiveRecord::Base

	belongs_to	:user
	has_many		:collaborative_prayers, :dependent => :destroy
	has_many		:collaborators, :through => :collaborative_prayers, :source => :user
	has_many		:answers, :dependent => :destroy


	validates_presence_of     :topic
	# we will slice topic
	# validates_length_of       :topic, :within => 1..153


	before_save		:polish_topic
	after_create	:collaborate_by_self

	def owned_by?(signed_user)
		!signed_user.blank? && self.user == signed_user
	end

	def has_collaborated_with?(user)
		return !user.blank? && self.collaborators.include?(user)
	end

	protected

		def polish_topic
			return if topic.blank?
			self.topic = self.topic.gsub(/[\ca-\cz]/, ' ')
			self.topic = self.topic.chars.slice(0,153)
		end

		def collaborate_by_self
			unless self.user_id.blank?
				new_collaborator = self.collaborative_prayers.new(:user_id => self.user_id)
				unless new_collaborator.save
					self.destroy and return false
				end
			end
		end
end
